package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Voice;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.VoiceApi;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class VoiceApiImpl implements VoiceApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserInfoApi userInfoApi;
    @Override
    public void save(Voice voice) {
        mongoTemplate.save(voice);
    }

    @Override
    public List<Voice> findVoice(Long userId, String gender) {
        UserInfo userInfo = userInfoApi.findById(userId);
        Query query = new Query();
        Criteria criteria = new Criteria();
        Criteria criteriaOrA = new Criteria().norOperator(Criteria.where("userId").is(userId));
        Criteria criteriaOrB = new Criteria().norOperator(Criteria.where("gender").is(gender));
        Criteria criteriaOrC = new Criteria().andOperator(Criteria.where("age").gte(userInfo.getAge() - 5).lte(userInfo.getAge() + 5));
        criteria.andOperator(criteriaOrA,criteriaOrB,criteriaOrC);

        List<Voice> voiceList = mongoTemplate.find(query.addCriteria(criteria).with(Sort.by(Sort.Order.desc("created"))).limit(10), Voice.class);
        List<ObjectId> collect = voiceList.stream().map(Voice::getId).collect(Collectors.toList());
        mongoTemplate.remove(Query.query(Criteria.where("_id").in(collect)),Voice.class);
        return voiceList;
    }
}